package study.javase.net.udp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 数据发送方 or 数据接收方
 *
 * @author LiShaowen
 * @date 2020/9/5 21:23
 */
public class UdpTalker001 {
    public static void main(String[] args) throws Exception {
        System.out.println("talker001准备就绪");
        // 1.使用DatagramSocket 指定端口创建发送端
        DatagramSocket sender = new DatagramSocket(8888);
        // 2.准备数据 将数据转成字节组
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String data = reader.readLine();
            byte[] byteData = data.getBytes();
            // 3.封装成DategramPacket包裹，需要制定目的地
            DatagramPacket packet = new DatagramPacket(byteData,0,byteData.length,new InetSocketAddress("localhost",9999));
            // 4.发送包裹
            sender.send(packet);
            if ("bye".equals(data)) {
                break;
            }
        }
        // 5.释放资源
        sender.close();

    }
}
